package config

import (
	"encoding/json"
	"fmt"
	"os"

	"github.com/go-redis/redis/v8"
)

// QueueSettings ...
type QueueSettings struct {
	LockDuration      int64 `json:"lock_duration,omitempty"`
	MaxStalledCount   int64 `json:"max_stalled_count,omitempty"`
	StalledInterval   int64 `json:"stalled_interval,omitempty"`
	LockRenewTime     int64 `json:"lock_renew_time,omitempty"` // LockDuration/2
	RetryProcessDelay int64 `json:"retry_process_delay,omitempty"`
	DrainDelay        int64 `json:"drain_delay,omitempty"`
	GuardInterval     int64 `json:"guard_interval,omitempty"`
}

// QueueKeys ...

// Config ... 初始化配置选项
type Config struct {
	KeyPrefix     string         `json:"key_prefix,omitempty"`
	Name          string         `json:"name,omitempty"`
	RedisOptions  *redis.Options `json:"redis_options,omitempty"`
	QueueSettings *QueueSettings `json:"queue_settings,omitempty"`
}

// NewFromJSON ... 从json文件读取配置
func NewFromJSON(cnfPath string) (*Config, error) {
	cnf := new(Config)
	file, err := os.Open(cnfPath)
	if err != nil {
		return nil, fmt.Errorf("open config file error: %s", err)
	}
	data := make([]byte, 1000)
	count, err := file.Read(data)
	if err != nil {
		return nil, fmt.Errorf("Read from file error: %s", err)
	}

	if err := json.Unmarshal(data[:count], cnf); err != nil {
		return nil, fmt.Errorf("Unmarshal config error: %s", err)
	}

	return cnf, nil
}
